package com.ygy.jxc.service.Impl;

import com.ygy.jxc.model.XtmdAdmin;
import com.ygy.jxc.model.XtmdRole;
import com.ygy.jxc.service.XtAdminService;
import com.ygy.jxc.service.XtRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证校验的方法
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    XtAdminService sysUserService;

    @Autowired
    XtRoleService sysRoleService;

    //前端访问 /login时进入此方法
    /**
     * 完成账号的校验
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    //是前端的 还是数据库中的？ username是前端的
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        System.out.println("开始账号校验********************");
        //传不过来
       // String loginname="admin";
//        System.out.println("获取用户名:"+username);
        // 1.需要根据账号查询
        List<XtmdAdmin> list = sysUserService.queryByUserName(username);
        if(list != null && list.size() == 1){
            // 账号是存在的
            XtmdAdmin sysUser = list.get(0);
//            System.out.println("登陆名"+sysUser.getUserName());
            // 根据当前登录的账号查询到关联的角色信息
            /**
             * 通过userid获取角色 （需要关系表查）
             */
            List<XtmdRole> sysRoles = sysRoleService.queryByUserId(sysUser.getId());
//     *******************************测试***********************************************
//          System.out.println("当前登陆用户的角色："+sysRoles.toString());
                 //输出
            //A granted authority textual representation is required  角色要为英文的 驼峰命名法
            XtmdRole xtmdRole = sysRoles.get(0);
        //    System.out.println("角色输出"+xtmdRole.toString());
//            System.out.println("角色名:"+xtmdRole.getRoleName());
            List<GrantedAuthority> listRole = new ArrayList<>();
            if(sysRoles != null && sysRoles.size() > 0){
                for (XtmdRole sysRole : sysRoles) {
                    listRole.add(new SimpleGrantedAuthority(sysRole.getRoleName()));
                }
            }
            // 密码模拟的是就数据库查询出来  登陆的 不是真实的名
            return new User(sysUser.getUserName(),sysUser.getPassword(),listRole);
        }
        return null;
    }
}
